//
//  SearchViewController.m
//  video
//
//  Created by lanou3g on 15/5/28.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "SearchViewController.h"
#import "URL.h"
#import "SearchDetailViewController.h"
#import "SearchCell.h"
#import "UIImageView+WebCache.h"

@interface SearchViewController ()

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.videoArray=[NSMutableArray array];
   
    //tableView添加背景图
    UIImageView* imgView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"lol3"]];
    self.tableView.backgroundView=imgView;
    [self layout];
    
//    __weak SearchViewController*searchVC=self;
//    // 添加传统的下拉刷新
//    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
//    [self.tableView addLegendHeaderWithRefreshingBlock:^{
//        [searchVC loadNewData];

//    }];

    // 添加传统的下拉刷新
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    // 添加传统的上拉刷新
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadOnceData方法）
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
    
    
    
    //注册
    [self.tableView registerNib:[UINib nibWithNibName:@"SearchCell" bundle:nil] forCellReuseIdentifier:@"myCell"];
    [self showUploadPicture];
   
    }
#pragma mark - 数据处理相关
#pragma mark 下拉刷新数据
-(void)loadNewData{
    self.page=1;
   
    [self.videoArray removeAllObjects];
    [self getDataByPage:self.page];
    [self.tableView reloadData];//****记得,不然报错
    [self.tableView.header endRefreshing];



}
#pragma mark 上拉加载更多数据
- (void)loadMoreData{
    self.page++;
    [self getDataByPage:self.page];
    [self.tableView.footer endRefreshing];


}


-(void)layout{
    UIBarButtonItem*LeftBI=[[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem=LeftBI;
    LeftBI.tintColor=[UIColor yellowColor];

}

//未加载时显示加载提示
-(void)showUploadPicture{
    //大菊花展
    self.hud = [[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:self.hud];
    self.hud.labelText=@"拼命加载中";
    [self.hud show:YES];

}


//返回
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)getDataByPage:(NSInteger)page{
    
    
    //汉字转码
    NSString*dataUTF8=[self.str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString*urlString=[NSString stringWithFormat:SearchVideo,dataUTF8,page];
    NSURL*url=[NSURL URLWithString:urlString];
    NSURLRequest*request=[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
       
        if(data==nil){
            
            return ;
        }
        NSMutableArray*array=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        for(NSMutableDictionary*dic in array){
            BoxVideo*boxVideo=[[BoxVideo alloc]init];
            [boxVideo setValuesForKeysWithDictionary:dic];
            [self.videoArray addObject:boxVideo];
        
        }

        [self.tableView reloadData];
    }];

   // NSLog(@"%@",self.videoArray);

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Return the number of rows in the section.
    return self.videoArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
    if(!cell){
    
        cell=[[SearchCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myCell"];
    
    }
    // Configure the cell...
    BoxVideo*boxVideo=self.videoArray[indexPath.row];
    cell.titleLabel.text=boxVideo.title;
    
    //第三方加载图片,取消菊花展
    [cell.imgView sd_setImageWithURL:[NSURL URLWithString:boxVideo.cover_url]completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [self.hud removeFromSuperview];
        
    }];
        cell.backgroundColor=[UIColor clearColor];
    
   // NSLog(@"%@",cell.titleLabel.text);
# pragma mark---自定义文本高度必须要做的两件事第一步:
   
    cell.titleLabel.font=Font_17;
    cell.titleLabel.numberOfLines=0;
#pragma mark---第三步:重新设置label高度
    //[self class]获取self所属的类
    CGFloat height=[[self class] textLabelHeight:cell.titleLabel.text] ;
    //把的高度重新设置
    
    CGRect frame=cell.titleLabel.frame;
    frame.size.height=height;
    cell.titleLabel.frame=frame;
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   BoxVideo*video= self.videoArray[indexPath.row];
    CGFloat height=[SearchViewController textLabelHeight:video.title];
    if(height<80){
        return 140;
    }
    else{
        return 60+height;
    }

}
//进入详情视频页面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    BoxVideo*boxVideo=self.videoArray[indexPath.row];
    SearchDetailViewController*searchDVC=[[SearchDetailViewController alloc]init];
    searchDVC.str=boxVideo.vid;
    searchDVC.videoTitle=boxVideo.title;
    [self.navigationController pushViewController:searchDVC animated:YES];
    self.tabBarController.tabBar.hidden=YES;//隐藏tabBar

}
//恢复tabBar
-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden=NO;

}
#pragma mark---自适应高度第二步:获取文本高度
//获取文本的高度
+(CGFloat)textLabelHeight:(NSString*)text{
    
    //iOS7.0以后计算文本高度要使用到的方法,它返回的是一个矩形区域
    //1.限定宽高(高,基本没用,可以超出)
    CGSize size=CGSizeMake(0.5*CGRectGetWidth([UIScreen mainScreen].bounds)-30, 1000);//限定宽度不能比label宽度大了(宽度一样即可)
    //将字体和字体大小存放到字典中
    NSDictionary*dic=@{NSFontAttributeName:[UIFont systemFontOfSize:14.0]};
    CGRect rect=[text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
